package controllers;

import helpers.DateHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import services.UpdateDomain;

import models.Domain;

public class UpdateSiteInfo extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String domainName = path.toLowerCase().replaceAll("/u/", "");
		String allow = (String) request.getParameter("allow");
		boolean isAllow = false;
		if (allow != null) {
			try {
				isAllow = Boolean.parseBoolean(allow);
			} catch (Exception e) {
				
			}
		}
		
		if (UrlHelper.checkDomain(domainName) && isAllow) {
			Boolean update = true;
			try {
				Objectify ofy = ObjectifyService.begin();
				//View data
				Domain domain = new Domain();
				try {
					domain = ofy.get(new Key<Domain>(Domain.class, domainName));
					List<Long> d = DateHelper.coundownFromNow(domain.getUpdated());
					if (d.get(0) <= 0 || d.get(1) <= 0 || d.get(2) <= 0) {
						update = true;
					} else {
						update = false;
					}
					//Domain domain = ofy.get(Domain.class, domainName);
				} catch (Exception e) {
					update = true;
				}
				
				//DomainDebug.debugWeb(domain, response);
				
			} catch (Exception e) {
				update = true;
				// TODO: handle exception
			}
			
			if (update) {
				new UpdateDomain(domainName);
				response.getWriter().println("<a href=\"/s/" + domainName + "\">View domain " + domainName + "</a>");
				
				//Clear cache
				Cache cache=null;
				try {
		            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		        } catch (CacheException e) {
		           e.printStackTrace();
		        }
		        
		        String cachename = "s_" + domainName;
		        cache.remove(cachename);
		        response.getWriter().println("");
			} else {
				response.getWriter().println("<a href=\"/s/" + domainName + "\">View info " + domainName + "</a>");
				//response.getWriter().println("update unsuccess");
			}
		}
	}
}
